var constants = require('/constants.js');
var crc16 = require('/crc_modbus.js');
// page的实例对象 用来回调处理结果回去 
var _this = null
var discovering = false
var available = false
var name = ''
var deviceId = ''
var characteristicId = ''
var serviceId = ''
var timeId = null
var blt = null


function initBluetooth(that) {
    _this = that
    name = that.data.name
    // 版本过低兼容
    if (!wx.openBluetoothAdapter) {
        _this.bleStateListener(constants.LOW_BLE_STATUS)
    }
    wx.openBluetoothAdapter({
        success(res) {
            _this.bleStateListener(constants.OPEN_BLE_STATUS)
            console.log("初始化蓝牙模块 --- 已开启")
            watchBluetoothStateChange()
            searchBluetooth()
        },
        fail(err) {
            console.log("初始化蓝牙模块 --- WEI开启")
            _this.bleStateListener(constants.NOT_BLE_STATUS)
        }
    })
}

/**
 * 监听蓝牙状态改变
 */
function watchBluetoothStateChange() {
    wx.onBluetoothAdapterStateChange((res) => {
        console.log("监听蓝牙状态改变", res)
        /**
         * 搜索状态
         */
        if (discovering != res.discovering) {
            discovering = res.discovering
        }
        /**
         * 蓝牙状态
         */
        if (available != res.available) {
            available = res.available
            if (!res.available) {
                _this.bleStateListener(constants.NOT_LONG_BLE_STATUS)
                console.log('蓝牙适配器不可用')
            } else {
                if (!res.discovering && !devices.length) {
                    //查询蓝牙
                    searchBluetooth()
                }
            }
        }
    })
}

/**
 * 查找设备（20s 停止搜索）
 */
function searchBluetooth() {
    wx.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: false,
        success(res) {
            console.log("查找设备")
            watchBluetoothFound()
            // 20s 停止搜索
            // setTimeout(noSearchBluetooth, 20000)
            blt = setTimeout(function () {
                console.log('blt')
                console.log(blt)
                if(blt){
                    noSearchBluetooth();
                }
                // closeConnectBluetooth()
            },20000)
        }
    })
}

function noSearchBluetooth(){
    console.log("搜索蓝牙失败")
    _this.bleStateListener(constants.NO_SEARCH_BLE_STATUS)
    stopSearchBluetooth
}

/**
 * 监听寻找到新设备
 */
function watchBluetoothFound() {
    wx.onBluetoothDeviceFound(function (res) {
        let device = res.devices[0]
        if (device.localName && device.localName==name) {
            console.log('查找到', name, '设备id', device.deviceId)
            deviceId = device.deviceId
            console.info('连接成功---', deviceId)
            if(blt){
                blt = null
                clearTimeout(blt);
            }
            connectBluetooth()
            // 连接成功 需要断开蓝牙搜索
            stopSearchBluetooth()
        }
    })
}


/**
 * 停止查找
 */
function stopSearchBluetooth() {
    wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
            console.log("停止查找")
        }
    })
}

/**
 * 连接设备
 */
function connectBluetooth() {
    wx.createBLEConnection({
        deviceId: deviceId,
        success(res) {
            console.info('connectBluetooth', deviceId)
            console.log("连接成功设备---" + JSON.stringify(res))
            getBluetoothServers()
        },
        fail(err) {
            closeConnectBluetooth()
            console.log("连接失败，结束---")
        }
    })
}

/**
 * 断开连接
 */
function closeConnectBluetooth() {
    // 断开BLE的连接
    wx.closeBLEConnection({
        deviceId: deviceId,
        success(res) {
            console.log("手动断开连接")
        }
    })
    // 断开蓝牙的连接 （初始化所有的状态）
    wx.closeBluetoothAdapter({
        success(res) {
            name = '',
                deviceId = '',
                serviceId = '',
                characteristicId = ''
        }
    })
}

/**
 * 获取设备服务
 */
function getBluetoothServers() {
    wx.getBLEDeviceServices({
        deviceId: deviceId,
        success(res) {
            console.log('获取设备服务', res.services)
            serviceId = res.services[0].uuid
            getBluetoothCharacteristics()
        },
    })
}

/**
 * 获取设备某个服务特征值列表
 */
function getBluetoothCharacteristics() {
    wx.getBLEDeviceCharacteristics({
        deviceId: deviceId,
        serviceId: serviceId,
        success(res) {
            console.info('获取设备某个服务特征值列表', res)
            characteristicId = res.characteristics[0].uuid
            notifyBluetoothCharacteristicValueChange()
        },
    })
}

/**
 * 启用设备特征值变化时的 notify 功能
 */
function notifyBluetoothCharacteristicValueChange() {
    wx.notifyBLECharacteristicValueChange({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        state: true,
        type: 'notification',
        success(res) {
            console.log("启用设备特征值变化时的 notify 功能", res)
            watchBluetoothCharacteristicValueChange()
        },
    })
}

/**
 * 监听设备的特征值变化
 */
function watchBluetoothCharacteristicValueChange() {
    console.log("监听设备的特征值变化")
    wx.onBLECharacteristicValueChange(function (res) {
        var flag = crc16.judgeData(ab2hex(res.value))
        console.log('状态码', flag)
        if(timeId){
            console.log('timeId', timeId)
            clearTimeout(timeId);
            timeId = null;
        }
        if (flag == '20') {
            //开锁成功
            _this.bleStateListener(constants.SUCCESS_LOCK_STATUS)
            // closeConnectBluetooth()
        } else if (flag == '22') {
            //蓝牙关锁成功
            _this.bleStateListener(constants.CLOSE_LOCK_STATUS)
            closeConnectBluetooth()
        }else if (flag == '21') {
            //设备正常
            _this.bleStateListener(constants.NORMAL_LOCK_STATUS)
        } else if (flag == '31') {
            //蓝牙异常
            _this.bleStateListener(constants.BLE_ALARM_STATUS)
            closeConnectBluetooth()
        }else if (flag == '33') {
            //锁开启异常
            _this.bleStateListener(constants.OPEN_LOCK_ALARM_STATUS)
            closeConnectBluetooth()
        }else if (flag == '34') {
            //锁关闭异常
            _this.bleStateListener(constants.CLOSE_LOCK_ALARM_STATUS)
            closeConnectBluetooth()
        } else {
            _this.bleStateListener(constants.OTHER_STATUS)
            closeConnectBluetooth()
        }
    })
    setTimeout(() => {
        writeBluetoothCharacteristicValue(name, 0)
    }, 20)
}
/**
 * 向设备特征值中写入二进制数据
 */
function writeBluetoothCharacteristicValue(param, f) {
    timeId = setTimeout(function () {
        if(timeId){
            _this.bleStateListener(constants.NO_RES_STATUS)
        } 
        // closeConnectBluetooth()
    },20000)
    // 写入指令 
    param = crc16.parseOpenData(param, f)
    let hh = hex2ab(strToHexCharCode(param));
    wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        // value: that.strToBuf(arr),
        value: hh,
        success(res) {
            console.log("写入成功")
        },
        fail(res) {
            console.log("写入失败 结束")
        }
    })
}

/**
 * hex转ArrayBuffer
 */
function strToBuf(arr) {
    var length = arr.length
    var buffer = new ArrayBuffer(length + 2)
    var dataview = new DataView(buffer)
    for (let i = 0; i < length; i++) {
        dataview.setUint8(i, '0x' + arr[i])
    }
    return buffer
}

// 16进度 转化 string
function hexToString(hex) {
    var string = '';
    for (var i = 0; i < hex.length; i += 2) {
        string += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
    }
    return string;
}
// 16进制转字符串
function strToHexCharCode(str) {
    if (str === "")
        return "";
    var hexCharCode = [];
    hexCharCode.push("0x");
    for (var i = 0; i < str.length; i++) {
        hexCharCode.push((str.charCodeAt(i)).toString(16));
    }
    return hexCharCode.join("");
}
// 16进制字符串转ArrayBuffer
function hex2ab(str) {
    if (!str) {
        return new ArrayBuffer(0);
    }
    let typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map(function (h) {
        return parseInt(h, 16)
    }));
    let buffer1 = typedArray.buffer;
    console.log(buffer1);
    return buffer1;
}
//字符串转16进制
function hexCharCodeToStr(hexCharCodeStr) {
    var trimedStr = hexCharCodeStr.trim();
    var rawStr =
        trimedStr.substr(0, 2).toLowerCase() === "0x"
            ?
            trimedStr.substr(2)
            :
            trimedStr;
    var len = rawStr.length;
    if (len % 2 !== 0) {
        alert("Illegal Format ASCII Code!");
        return "";
    }
    var curCharCode;
    var resultStr = [];
    for (var i = 0; i < len; i = i + 2) {
        curCharCode = parseInt(rawStr.substr(i, 2), 16); // ASCII Code Value
        resultStr.push(String.fromCharCode(curCharCode));
    }
    return resultStr.join("");
}
// 16进制字符串取需要的字节(fe 08 01 00 01 01 01 7a0b 008f)
function hexSlice(hex) {
    // 取k8位
    let k8 = hex.slice(14, 16);
    //取k9位
    let k9 = hex.slice(16, 18);
    return parseInt(k9 + k8, 16);
}
//解析ArrayBuffer类型数据
function ab2hex(e) {
    for (var a = e, i = new DataView(a), n = "", s = 0; s < i.byteLength; s++) 
    n += String.fromCharCode(i.getUint8(s));
    return n
}

module.exports = {
    initBluetooth,//初始化蓝牙模块
    writeBluetoothCharacteristicValue
}